<script setup lang="ts">
import { api } from '@/api/api'
import { useStandard_Parameterstore, type CreateParameter } from '@/stores/AllYouNeedIsStore'
import { onBeforeMount, ref, toRef, watch } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessageBox, ElTable } from 'element-plus'
import type { User } from '@/types/userType'
import { useUserStore } from '@/stores/user'

const route = useRoute()
const standardParameterStore = useStandard_Parameterstore()
const userInfo = useUserStore()

let parameterList = toRef(
  standardParameterStore.standards.find((x) => {
    return x.id == parseInt(route.params._id.toString())
  })?.parameters ?? []
)

watch(
  () => route.params,
  (params) => {
    if (params._id == undefined) {
      return
    }
    parameterList = toRef(
      standardParameterStore.standards?.find((x) => {
        return x.id == parseInt(params._id.toString())
      })?.parameters ?? []
    )
  }
)

function addParameter() {
  let x: CreateParameter = {
    name: '',
    emps: [],
    edit: true,
    humanList: [],
    equipmentList: [],
    sample: {
      informationFile: '',
      photo: '',
      followStandard: true
    },
    sop: {
      file: '',
      followStandard: true
    },
    facilityList: [],
    compareValidList: [],
    simulation: {
      report: '',
      origin: '',
      followStandard: true
    },
    status: 'Uncompleted',
    labAdmin: {
      id: userInfo.userInfo.id ?? -1,
      username: '',
      type: ''
    }
  }
  parameterList.value.push(x)
}

function deleteParameter(x: number) {
  parameterList.value.splice(x, 1)
}

function validate(scope: any) {
  if (scope.row.name == '') {
    ElMessageBox.alert('请输入参数名称！', '错误', {
      confirmButtonText: '确定'
    })
  } else if (scope.row.emps.length == 0) {
    ElMessageBox.alert('请选择负责员工！', '错误', {
      confirmButtonText: '确定'
    })
  } else {
    scope.row.edit = false
  }
}

//员工选择相关
const empsList = ref<User[]>([])
const selectTableRef = ref<InstanceType<typeof ElTable>>()

onBeforeMount(() => {
  api.getAllEmps().then((resp) => {
    empsList.value = resp
  })
})

const chooseEmpsDialogVisible = ref(false)

let currentEmpsList: User[] = []

function chooseEmps(emps: User[]) {
  chooseEmpsDialogVisible.value = true
  currentEmpsList = emps
  let [...temp] = currentEmpsList
  selectTableRef.value?.clearSelection()
  if (temp.length != 0) {
    temp.forEach((x) => {
      selectTableRef.value?.toggleRowSelection(x, true)
    })
  }
}

const handleSelectionChange = (val: User[]) => {
  currentEmpsList.splice(0, currentEmpsList.length)
  for (let x of val) {
    currentEmpsList.push(x)
  }
}

function confirmEmps() {
  chooseEmpsDialogVisible.value = false
}

function deleteEmp(emps: User[], emp: User) {
  emps.splice(
    emps.findIndex((x) => {
      return x.id == emp.id
    }),
    1
  )
}
</script>

<template>
  <el-table :data="parameterList">
    <el-table-column type="index"></el-table-column>
    <el-table-column label="参数名称">
      <template #default="scope">
        <span v-if="!scope.row.edit">{{ scope.row.name }}</span>
        <el-input v-else v-model="scope.row.name" placeholder="请输入参数名称">{{
          scope.row.name
        }}</el-input>
      </template>
    </el-table-column>
    <el-table-column label="负责人">
      <template #default="scope">
        <div v-if="!scope.row.edit">
          <el-tag v-for="emp in scope.row.emps" :key="emp.id" style="margin-right: 10px">
            {{ emp.username }}
          </el-tag>
        </div>
        <div v-else>
          <el-tag
            v-for="emp in scope.row.emps"
            :key="emp.id"
            closable
            @close="deleteEmp(scope.row.emps, emp)"
            style="margin-right: 10px"
          >
            {{ emp.username }}
          </el-tag>
          <el-button type="primary" @click="chooseEmps(scope.row.emps)">选择负责人</el-button>
        </div>
      </template>
    </el-table-column>
    <el-table-column label="">
      <template #default="scope">
        <el-button type="primary" v-if="scope.row.edit == false" @click="scope.row.edit = true"
          >编辑</el-button
        >
        <div v-else>
          <el-button type="success" @click="validate(scope)"
            ><el-icon> <Check /> </el-icon
          ></el-button>
          <el-button type="danger" @click="deleteParameter(scope.$index)"
            ><el-icon> <Delete /> </el-icon
          ></el-button>
        </div> </template
    ></el-table-column>
  </el-table>
  <el-button type="primary" @click="addParameter">添加参数</el-button>

  <el-dialog v-model="chooseEmpsDialogVisible" title="选择员工">
    <el-table :data="empsList" @selection-change="handleSelectionChange" ref="selectTableRef">
      <el-table-column type="index"></el-table-column>
      <el-table-column property="id" label="ID" />
      <el-table-column property="username" label="用户名" />
      <el-table-column type="selection"></el-table-column>
    </el-table>
    <template #footer>
      <el-button type="primary" @click="confirmEmps()">确定</el-button>
    </template>
  </el-dialog>
</template>

<style scoped></style>
